package com.maidou.qiantai.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.maidou.qiantai.common.constant.SpuConstant;
import com.maidou.qiantai.common.utils.util.StringUtil;
import com.maidou.qiantai.common.utils.util.WebUtils;
import com.maidou.qiantai.domain.*;
import com.maidou.qiantai.vo.spu.*;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.maidou.qiantai.mapper.SpuMapper;
import com.maidou.qiantai.service.ISpuService;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 商品Service业务层处理
 * 
 * @author maidou
 * @date 2024-03-13
 */
@Service
public class SpuServiceImpl implements ISpuService 
{
    @Resource
    private SpuMapper spuMapper;

    @Resource
    private SpuImageServiceImpl spuImageService;

    @Resource
    private ProductAttrValueServiceImpl productAttrValueService;

    @Resource
    private AttrAttrgroupRelationServiceImpl attrAttrgroupRelationService;

    @Resource
    private AttrGroupServiceImpl attrGroupService;

    @Resource
    private AttrServiceImpl attrService;

    @Resource
    private SkuServiceImpl skuService;
    @Resource
    private OsRecordServiceImpl osRecordService;
    @Resource
    private SpuCommentServiceImpl spuCommentService;
    @Resource
    private SpuCommentImageServiceImpl spuCommentImageService;

    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public Spu selectSpuById(Long id)
    {
        return spuMapper.selectSpuById(id);
    }

    /**
     * 查询商品列表
     * 
     * @param spu 商品
     * @return 商品
     */
    @Override
    public List<Spu> selectSpuList(Spu spu)
    {
        return spuMapper.selectSpuList(spu);
    }

    /**
     * 新增商品
     * 
     * @param spu 商品
     * @return 结果
     */
    @Override
    public int insertSpu(Spu spu)
    {
        spu.setCreateTime(DateUtils.getNowDate());
        return spuMapper.insertSpu(spu);
    }

    /**
     * 修改商品
     * 
     * @param spu 商品
     * @return 结果
     */
    @Override
    public int updateSpu(Spu spu)
    {
        spu.setUpdateTime(DateUtils.getNowDate());
        return spuMapper.updateSpu(spu);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteSpuByIds(Long[] ids)
    {
        return spuMapper.deleteSpuByIds(ids);
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteSpuById(Long id)
    {
        return spuMapper.deleteSpuById(id);
    }

    /**
     * 商品推荐
     * @return
     */
    @Override
    public List<SpuRecommendVo> selectRecommendSpuList(String keyword) {
        Spu spu = new Spu();
        spu.setPublishStatus(SpuConstant.SpuEnum.DOWN_SPU.type);
        spu.setSpuName(keyword);
        List<Spu> spus = spuMapper.selectRecommendSpuList(spu);
        List<SpuRecommendVo> collect = spus.stream().map(item -> {
            SpuRecommendVo spuRecommendVo = new SpuRecommendVo();
            BeanUtils.copyProperties(item, spuRecommendVo);
            return spuRecommendVo;
        }).collect(Collectors.toList());
        SpuRecommendVo spuRecommendVo = new SpuRecommendVo();
        spuRecommendVo.setNum(new PageInfo(spus).getTotal());
        spuRecommendVo.setId(0l);
        collect.add(0,spuRecommendVo);
        return collect;
    }

    /**
     * 根据分类id查询商品信息（排序）
     * @return
     */
    @Override
    public List<SpuRecommendVo> selectCatalogSpuList() {
        HttpServletRequest httpServletRequest = WebUtils.getHttpServletRequest();
        Object type = WebUtils.getRequestParameter("type");
        Object keyWord = WebUtils.getRequestParameter("keyWord");
        Object catalogId = WebUtils.getRequestParameter("catalogId");
        Integer integer = JSONObject.parseObject(JSON.toJSONString(type), Integer.class);
        String key = JSONObject.parseObject(JSON.toJSONString(keyWord), String.class);
        Long catalog_id = JSONObject.parseObject(JSON.toJSONString(catalogId), Long.class);
        Spu spu = new Spu();
        spu.setPublishStatus(SpuConstant.SpuEnum.DOWN_SPU.type);
        spu.setCatalogId(catalog_id);
        spu.setSpuName(key);
        List<Spu> spus = new ArrayList<>();
        if (ObjectUtils.isEmpty(type)||integer==0){
            spus = spuMapper.selectRecommendSpuList(spu);
        }else {
            spus  = spuMapper.selectCatalogSpuList(spu);
        }
        List<SpuRecommendVo> collect = spus.stream().map(item -> {
            SpuRecommendVo spuRecommendVo = new SpuRecommendVo();
            BeanUtils.copyProperties(item, spuRecommendVo);
            return spuRecommendVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询商品详情信息
     * @param spuId
     * @return
     */
    @Override
    public SpuInfoVo selectSpuInfo(Long spuId) {
        //添加商品浏览记录
        Long memberId =null;
        try {
            memberId = WebUtils.getMemberIdByAccessToken();
        }catch (Exception e){

        }
        if (memberId!=null){
            OsRecord osRecord = new OsRecord();
            osRecord.setSpuId(spuId);
            osRecord.setMemberId(memberId);
            List<OsRecord> osRecords = osRecordService.selectOsRecordList(osRecord);
            osRecord.setCreateTime(new Date());
            osRecord.setUpdateTime(new Date());
            if (osRecords.size()==0){
                osRecord.setIsDelete(0);
                osRecordService.insertOsRecord(osRecord);
            }else{
                osRecordService.updateOsRecordBySpuIdAndMemberId(osRecord);
            }
        }
        //商品基本信息
        Spu spu = spuMapper.selectSpuById(spuId);
        SpuInfoVo spuInfoVo = new SpuInfoVo();
        BeanUtils.copyProperties(spu,spuInfoVo);
        //商品头图信息
        SpuImage spuImage = new SpuImage();
        spuImage.setSpuId(spuId);
        spuImage.setType(SpuConstant.SpuImageEnum.INDEX.type);
        List<SpuImage> spuImages = spuImageService.selectSpuImageList(spuImage);
        spuInfoVo.setSpuHeadImages(spuImages);
        //商品详情图信息
        spuImage.setType(SpuConstant.SpuImageEnum.DETAIL.type);
        List<SpuImage> spuImagesInfo = spuImageService.selectSpuImageList(spuImage);
        spuInfoVo.setSpuInfoImages(spuImagesInfo);
        //商品基本属性
        ProductAttrValue productAttrValue = new ProductAttrValue();
        productAttrValue.setSpuId(spuId);
        productAttrValue.setQuickShow(1);
        List<ProductAttrValue> productAttrValues = productAttrValueService.selectProductAttrValueList(productAttrValue);
        List<Long> attrIds = productAttrValues.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //获取属性分组信息
        List<Long>  attrGroupIdByAttrId = attrAttrgroupRelationService.selectAttrGroupIdByAttrId(attrIds);
        //获取分组信息
        List<AttrGroup> attrGroups = attrGroupService.selectAttrGroupBatchById(attrGroupIdByAttrId);
        List<SpuAttrGroupVo> spuAttrGroupVos = attrGroups.stream().map(item -> {
            SpuAttrGroupVo spuAttrGroupVo = new SpuAttrGroupVo();
            BeanUtils.copyProperties(item, spuAttrGroupVo);
            return spuAttrGroupVo;
        }).collect(Collectors.toList());
        //封装分组下面的属性信息
        List<SpuAttrGroupVo> SpuAttrGroupVoList = spuAttrGroupVos.stream().map(item -> {
            List<ProductAttrValue> productList = productAttrValueService.selectProductAttrValueBatchByAttrIds(attrIds,spuId);
            item.setProductAttrValues(productList);
            return item;
        }).collect(Collectors.toList());
        spuInfoVo.setSpuAttrGroupVos(SpuAttrGroupVoList);
        //商品销售属性
        List<Attr> attrList = attrService.selectAttrBatchByIds(attrIds);
        List<SpuAttrVo> attrVos = attrList.stream().map(item -> {
            SpuAttrVo spuAttrVo = new SpuAttrVo();
            BeanUtils.copyProperties(item, spuAttrVo);
            List<String> list = StringUtil.stringValueSplit(item.getValueSelect());
            spuAttrVo.setValueSelectList(list);
            return spuAttrVo;
        }).collect(Collectors.toList());
        spuInfoVo.setSpuAttrVos(attrVos);
        //商品规格参数
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuService.selectSkuList(sku);
        List<SkuInfoVo> collect = skus.stream().map(item -> {
            SkuInfoVo skuInfoVo = new SkuInfoVo();
            BeanUtils.copyProperties(item, skuInfoVo);
            return skuInfoVo;
        }).collect(Collectors.toList());
        spuInfoVo.setSkuInfoVos(collect);
        //查询评论条数和统计评论好评度
        Integer commentNum = spuCommentService.selectSpuCommentNum(spuId);
        spuInfoVo.setCommentNum(commentNum);
        Integer commentGoodNum =  spuCommentService.selectSpuCommentGoodComment(spuId);
        spuInfoVo.setGoodComment(commentGoodNum);
        return spuInfoVo;
    }
}
